import React, { Component } from 'react';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import {
  Button,
  Row,
  Col,
  Input,
  Card,
  Tooltip,
  Modal,
  Radio,
  Select,
  message,
  TreeSelect,
  Form,
  Upload,
} from 'antd';
import ImageUploader from '../../components/Falcon/Attachment/ImageUploader';
import querystring from 'querystring';
import ChannelProductEditor from '../../components/Falcon/ChannelProductEditor';
import FooterToolbar from 'components/FooterToolbar';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Description from '../../components/Falcon/Description';
import { solo } from '../../common/solo';
import { wrapFileList } from '../../utils/utils';

const ButtonGroup = Button.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
};
const formItemLayout2 = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 21,
  },
};
const formItemLayout1 = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 16,
  },
};

let file = [];

@connect(({ channel, system }) => ({
  channel,
  system,
}))
@Form.create()
export default class ChannelDetailsUpdata extends Component {
  state = {
    dealerLevel: false,
    channelId: '',
    branchIdList: [],
    width: '100%',
    licenseImg: '',
    idImg: '',
    doorImg: '',
    agreementFileList: [],
    otherFileList: [],
    branchFlag: false,
    branchId: '',

    imgMap: {
      licenseImg: '',
      idImg: '',
      doorImg: '',
      hallImg: '',
      cardImg: '',
      bankCardImg: '',
    },

    fileList: {
      licenseImg: [],
      idImg: [],
      doorImg: [],
      hallImg: [],
      cardImg: [],
      bankCardImg: [],
    },

    attachmentMap: {
      agreement: [],
      other: [],
    },

    attachmentData: {
      cooperateProtocol: [],
      otherProtocol: [],
    },

    attachmentMapKey: {
      agreement: [],
      other: [],
    },
  };

  componentWillUnmount() {
    window.removeEventListener('resize', this.resizeFooterToolbar);
  }

  resizeFooterToolbar = () => {
    const sider = document.querySelectorAll('.ant-layout-sider')[0];
    const width = `calc(100% - ${sider.style.width})`;
    if (this.state.width !== width) {
      this.setState({ width });
    }
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    this.setState({
      channelId: params.channelId,
    });

    dispatch({
      type: 'system/getBranchTreeList',
    });

    dispatch({
      type: 'channel/detailsChannel',
      payload: {
        channelId: params.channelId,
      },
      callback: () => {
        const { channel: { channelDetails } } = this.props;
        // console.log("handleImageUploaded fieldName", channelDetails)
        let fileList = this.state.fileList;

        if (channelDetails.channel.licenseImg != '') {
          fileList.licenseImg.push({
            uid: channelDetails.channel.licenseImg,
            key: channelDetails.channel.licenseImg,
            name: channelDetails.channel.licenseImg,
            status: 'done',
            url: solo.imgShow + channelDetails.channel.licenseImg,
          });
        }
        if (channelDetails.channel.idImg != '') {
          fileList.idImg.push({
            uid: channelDetails.channel.idImg,
            key: channelDetails.channel.idImg,
            name: channelDetails.channel.idImg,
            status: 'done',
            url: solo.imgShow + channelDetails.channel.idImg,
          });
        }
        if (channelDetails.channel.doorImg != '') {
          fileList.doorImg.push({
            uid: channelDetails.channel.doorImg,
            key: channelDetails.channel.doorImg,
            name: channelDetails.channel.doorImg,
            status: 'done',
            url: solo.imgShow + channelDetails.channel.doorImg,
          });
        }
        if (channelDetails.channel.hallImg != '') {
          fileList.hallImg.push({
            uid: channelDetails.channel.hallImg,
            key: channelDetails.channel.hallImg,
            name: channelDetails.channel.hallImg,
            status: 'done',
            url: solo.imgShow + channelDetails.channel.hallImg,
          });
        }
        if (channelDetails.channel.cardImg != '') {
          fileList.cardImg.push({
            uid: channelDetails.channel.cardImg,
            key: channelDetails.channel.cardImg,
            name: channelDetails.channel.cardImg,
            status: 'done',
            url: solo.imgShow + channelDetails.channel.cardImg,
          });
        }
        if (channelDetails.channel.bankCardImg != '') {
          fileList.bankCardImg.push({
            uid: channelDetails.channel.bankCardImg,
            key: channelDetails.channel.bankCardImg,
            name: channelDetails.channel.bankCardImg,
            status: 'done',
            url: solo.imgShow + channelDetails.channel.bankCardImg,
          });
        }
        let attachmentMap = this.state.attachmentMap;
        if (channelDetails.channel.cooperateProtocol.length > 0) {
          for (let i = 0; i < channelDetails.channel.cooperateProtocol.length; i++) {
            attachmentMap.agreement.push({
              uid: channelDetails.channel.cooperateProtocol[i],
              key: channelDetails.channel.cooperateProtocol[i],
              name: channelDetails.channel.cooperateProtocol[i],
              status: 'done',
              url: solo.imgShow + channelDetails.channel.cooperateProtocol[i],
            });
          }
        }
        if (channelDetails.channel.otherProtocol.length > 0) {
          for (let i = 0; i < channelDetails.channel.otherProtocol.length; i++) {
            attachmentMap.other.push({
              uid: channelDetails.channel.otherProtocol[i],
              key: channelDetails.channel.otherProtocol[i],
              name: channelDetails.channel.otherProtocol[i],
              status: 'done',
              url: solo.imgShow + channelDetails.channel.otherProtocol[i],
            });
          }
        }
        this.setState({
          fileList,
          attachmentMap,
        });
      },
    });
    dispatch({
      type: 'system/fetchBasic',
    });
    window.addEventListener('resize', this.resizeFooterToolbar);
  }

  handleImageUploaded = (fieldName, fileList) => {
    switch (fieldName) {
      case '营业执照':
        this.setState({
          fileList: { ...this.state.fileList, licenseImg: fileList },
        });
        break;
      case '身份证照':
        this.setState({
          fileList: { ...this.state.fileList, idImg: fileList },
        });
        break;
      case '门头照':
        this.setState({
          fileList: { ...this.state.fileList, doorImg: fileList },
        });
        break;
      case '展厅照':
        this.setState({
          fileList: { ...this.state.fileList, hallImg: fileList },
        });
        break;
      case '名片':
        this.setState({
          fileList: { ...this.state.fileList, cardImg: fileList },
        });
        break;
      case '银行卡':
        this.setState({
          fileList: { ...this.state.fileList, bankCardImg: fileList },
        });
        break;
    }
  };

  handleRemoveImage = (fieldName, fileInfo) => {
    switch (fieldName) {
      case '营业执照':
        this.state.fileList.licenseImg = [];
        this.setState({
          fileList: { ...this.state.fileList, licenseImg: [] },
        });
        break;
      case '身份证照':
        this.state.fileList.idImg = [];
        this.setState({
          fileList: { ...this.state.fileList, idImg: [] },
        });
        break;
      case '门头照':
        this.state.fileList.doorImg = [];
        this.setState({
          fileList: { ...this.state.fileList, doorImg: [] },
        });
        break;
      case '展厅照':
        this.state.fileList.hallImg = [];
        this.setState({
          fileList: { ...this.state.fileList, hallImg: [] },
        });
        break;
      case '名片':
        this.state.fileList.cardImg = [];
        this.setState({
          fileList: { ...this.state.fileList, cardImg: [] },
        });
        break;
      case '银行卡':
        this.state.fileList.bankCardImg = [];
        this.setState({
          fileList: { ...this.state.fileList, bankCardImg: [] },
        });
        break;
    }
  };

  handleSubmitStep = () => {
    // console.log('this.state.fileList ', this.state.fileList);
    const { dispatch } = this.props;
    const { channel } = this.props;
    const { validateFieldsAndScroll } = this.props.form;
    const { channelUpdateProductDiviList, channelDetails } = channel;
    let attachmentMapKey = this.state.attachmentMapKey;
    if (this.state.attachmentMap.agreement.length > 0) {
      this.state.attachmentMap.agreement.map(item => {
        item.status == 'done'
          ? attachmentMapKey.agreement.push(item.key == undefined ? item.uid : item.key)
          : null;
      });
    }
    if (this.state.attachmentMap.other.length > 0) {
      this.state.attachmentMap.other.map(item => {
        item.status == 'done'
          ? attachmentMapKey.other.push(item.key == undefined ? item.uid : item.key)
          : null;
      });
    }
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        dispatch({
          type: 'channel/updateChannel',
          payload: {
            id: this.state.channelId,
            ...values,
            // ...this.state.fileList,
            branchId: this.state.branchFlag ? values.parentId : channelDetails.channel.branchId,
            bankCardImg:
              this.state.fileList.bankCardImg.length > 0
                ? this.state.fileList.bankCardImg[0].key
                : null,
            cardImg:
              this.state.fileList.cardImg.length > 0 ? this.state.fileList.cardImg[0].key : null,
            hallImg:
              this.state.fileList.hallImg.length > 0 ? this.state.fileList.hallImg[0].key : null,
            idImg: this.state.fileList.idImg.length > 0 ? this.state.fileList.idImg[0].key : null,
            licenseImg:
              this.state.fileList.licenseImg.length > 0
                ? this.state.fileList.licenseImg[0].key
                : null,
            doorImg:
              this.state.fileList.doorImg.length > 0 ? this.state.fileList.doorImg[0].key : null,
            cooperateProtocol: attachmentMapKey.agreement,
            otherProtocol: attachmentMapKey.other,
            productList: channelUpdateProductDiviList,
          },
          callback: () => {
            const { channel: { updateChannelResult, channelDetailsId } } = this.props;
            if (updateChannelResult.code == '200') {
              dispatch(routerRedux.push(`/channel/channel-details?id=${channelDetailsId}&state=1`));
              message.success('提交成功');
            } else {
              message.error(updateChannelResult.message);
            }
          },
        });
      }
    });
  };

  callbackStep = () => {
    this.props.dispatch(
      routerRedux.push(`/channel/channel-details?id=${this.state.channelId}&state=1`)
    );
  };

  handleSelectCustomerClick = () => {
    this.setState({
      dealerLevel: true,
    });
  };

  handleCancelDealerLevel = () => {
    this.setState({
      dealerLevel: false,
    });
  };

  handleBranchIdList = value => {
    this.setState({
      branchIdList: value,
      branchFlag: true,
    });
  };

  renderTreeNodesChildren = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode value={item.id} title={item.orgName} key={item.id} dataRef={item}>
            {this.renderTreeNodesChildren(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode value={item.id} key={item.id} dataRef={item} title={item.orgName} />;
    });
  };

  handleAttachmentUploadChange = (info, fieldName) => {
    const fileList = wrapFileList(info);
    if (info.file.status === 'done') {
      const attachmentMap = { ...this.state.attachmentMap };
      attachmentMap[fieldName] = fileList;
      this.setState({
        attachmentMap,
      });
      message.success(`文件上传成功`);
    } else if (info.file.status === 'error') {
      message.error('文件上传失败');
    }
  };

  handleRemoveFile = file => {
    const { dispatch } = this.props;
    dispatch({
      type: 'channel/deleteFile',
      payload: {
        fileId: file.uid,
      },
      callback: () => {
        const { channel: { channelResult } } = this.props;
        if (channelResult.code == 200) {
          message.success('删除成功');
          dispatch({
            type: 'channel/detailsChannel',
            payload: {
              channelId: this.state.channelId,
            },
          });
        } else {
          message.error(channelResult.message);
        }
      },
    });
  };

  // handleBeforeUpload = (file) =>{
  //   console.log("file", file)
  //     const isZip = file.type === 'file/zip';
  //     const isDoc = file.type === 'file/dox';
  //     const isDocx = file.type === 'file/docx';
  //     const isPdf = file.type === 'file/pdf';
  //     const isJPG = file.type === 'image/jpg';
  //     const isPNG = file.type === 'image/png';
  //     if(!isZip &&!isDoc && !isDocx && !isPdf && !isJPG && !isPNG ){
  //       message.error('文件格式错误!');
  //         return false;
  //     }
  //     return true;
  // }
  handleCallback = () => {
    window.history.back(-1);
  };

  render() {
    const { channel: { channelDetails, channelLoading } } = this.props;
    const { system: { allBranchTreeList } } = this.props;

    const { getFieldDecorator, getFieldValue, validateFieldsAndScroll } = this.props.form;

    const defaultAttachmentUploadProps = {
      name: 'file',
      action: solo.uploadImg,
      multiple: true,
      // beforeUpload: this.handleBeforeUpload,
      headers: {
        authorization: 'authorization-text',
      },
    };

    const agreementFileUploadProps = {
      ...defaultAttachmentUploadProps,
      defaultFileList: this.state.attachmentMap.agreement,

      onChange: info => {
        this.handleAttachmentUploadChange(info, 'agreement');
      },
      onRemove: file => {
        this.handleRemoveFile(file);
      },
    };

    const otherFileUploadProps = {
      ...defaultAttachmentUploadProps,
      defaultFileList: this.state.attachmentMap.other,
      onChange: info => {
        this.handleAttachmentUploadChange(info, 'other');
      },
      onRemove: file => {
        this.handleRemoveFile(file);
      },
    };

    return (
      <PageHeaderLayout title="信息修改">
        {/* {JSON.stringify(channelDetails)} */}
        <Card title="基本信息修改">
          <Row>
            <Form>
              {channelDetails && (
                <div>
                  <Row style={{ textAlign: 'centent' }}>
                    <Col span={12}>
                      <FormItem label="公司全称" {...formItemLayout}>
                        {getFieldDecorator('dealerName', {
                          initialValue: channelDetails.channel.dealerName,
                        })(<Input placeholder="请输入公司全称" />)}
                      </FormItem>
                    </Col>
                    <Col span={10}>
                      <FormItem label="经销商等级" {...formItemLayout1}>
                        {getFieldDecorator('rank', {
                          initialValue: channelDetails.channel.rank,
                        })(
                          <Select>
                            <Option value={'1'}>A</Option>
                            <Option value={'2'}>B</Option>
                            <Option value={'3'}>C</Option>
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={2}>
                      <Tooltip title="查看等级说明">
                        <Button
                          onClick={this.handleSelectCustomerClick}
                          style={{ marginTop: '5px' }}
                          type="dashed"
                          size="small"
                          shape="circle"
                          icon="info-circle"
                        />
                      </Tooltip>
                    </Col>
                  </Row>

                  <Row>
                    <Col span={12}>
                      <FormItem label="公司简称" {...formItemLayout}>
                        {getFieldDecorator('simpleName', {
                          initialValue: channelDetails.channel.simpleName,
                        })(<Input placeholder="请输入公司简称" />)}
                      </FormItem>
                    </Col>
                    {allBranchTreeList && (
                      <Col span={12}>
                        <FormItem label="所属组织" {...formItemLayout}>
                          {getFieldDecorator('parentId', {
                            initialValue: channelDetails.channel && channelDetails.channel.branchId,
                          })(
                            <TreeSelect
                              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                              placeholder="请选择"
                              allowClear
                              treeDefaultExpandAll
                              onChange={this.handleBranchIdList}
                            >
                              {allBranchTreeList && this.renderTreeNodesChildren(allBranchTreeList)}
                            </TreeSelect>
                          )}
                        </FormItem>
                      </Col>
                    )}
                  </Row>
                  <Row>
                    <Col span={12}>
                      <FormItem label="负责人" {...formItemLayout}>
                        {getFieldDecorator('leader', {
                          initialValue: channelDetails.channel.leader,
                        })(<Input placeholder="请输入负责人" />)}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem label="联系电话" {...formItemLayout}>
                        {getFieldDecorator('phone', {
                          initialValue: channelDetails.channel.phone,
                        })(<Input placeholder="请输入联系电话" />)}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={12}>
                      <FormItem label="垫资账户" {...formItemLayout}>
                        {getFieldDecorator('fundAccount', {
                          initialValue: channelDetails.channel.fundAccount,
                        })(<Input placeholder="请输入垫资账户" />)}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem label="开户银行" {...formItemLayout}>
                        {getFieldDecorator('depositBank', {
                          initialValue: channelDetails.channel.depositBank,
                        })(<Input placeholder="请输入开户银行" />)}
                      </FormItem>
                    </Col>
                  </Row>

                  <Row>
                    <Col span={12}>
                      <FormItem label="银行账户" {...formItemLayout}>
                        {getFieldDecorator('bankAccount', {
                          initialValue: channelDetails.channel.bankAccount,
                        })(<Input placeholder="请输入银行账户" />)}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem label="营业执照号" {...formItemLayout}>
                        {getFieldDecorator('licenseNo', {
                          initialValue: channelDetails.channel.licenseNo,
                        })(<Input placeholder="请输入营业执照号" />)}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={24}>
                      <FormItem label="照片上传" {...formItemLayout2}>
                        <Col span={4}>
                          <ImageUploader
                            fieldName="营业执照"
                            label="营业执照"
                            maxCount={1}
                            size="large"
                            showRemoveIconType={true}
                            onRemoveImage={this.handleRemoveImage}
                            fileList={this.state.fileList.licenseImg}
                            attachmentData={{
                              projectId: '', //业务ID
                              customerId: '', //客户ID
                              attachType: '0', //0：图片；1：视频
                              attachKind: '', //附件种类
                              type: '营业执照', //图片类型
                            }}
                            onImageUploaded={this.handleImageUploaded}
                          />
                        </Col>
                        <Col span={4}>
                          <ImageUploader
                            fieldName="身份证照"
                            label="身份证照"
                            maxCount={1}
                            size="large"
                            showRemoveIconType={true}
                            onRemoveImage={this.handleRemoveImage}
                            fileList={this.state.fileList.idImg}
                            attachmentData={{
                              projectId: '', //业务ID
                              customerId: '', //客户ID
                              attachType: '0', //0：图片；1：视频
                              attachKind: '', //附件种类
                              type: '身份证照', //图片类型
                            }}
                            onImageUploaded={this.handleImageUploaded}
                          />
                        </Col>
                        <Col span={4}>
                          <ImageUploader
                            fieldName="门头照"
                            label="门头照"
                            maxCount={1}
                            size="large"
                            showRemoveIconType={true}
                            onRemoveImage={this.handleRemoveImage}
                            fileList={this.state.fileList.doorImg}
                            attachmentData={{
                              projectId: '', //业务ID
                              customerId: '', //客户ID
                              attachType: '0', //0：图片；1：视频
                              attachKind: '', //附件种类
                              type: '门头照', //图片类型
                            }}
                            onImageUploaded={this.handleImageUploaded}
                          />
                        </Col>
                        <Col span={4}>
                          <ImageUploader
                            fieldName="展厅照"
                            label="展厅照"
                            maxCount={1}
                            size="large"
                            showRemoveIconType={true}
                            onRemoveImage={this.handleRemoveImage}
                            fileList={this.state.fileList.hallImg}
                            attachmentData={{
                              projectId: '', //业务ID
                              customerId: '', //客户ID
                              attachType: '0', //0：图片；1：视频
                              attachKind: '', //附件种类
                              type: '展厅照', //图片类型
                            }}
                            onImageUploaded={this.handleImageUploaded}
                          />
                        </Col>
                        <Col span={4}>
                          <ImageUploader
                            fieldName="名片"
                            label="名片"
                            maxCount={1}
                            size="large"
                            showRemoveIconType={true}
                            onRemoveImage={this.handleRemoveImage}
                            fileList={this.state.fileList.cardImg}
                            attachmentData={{
                              projectId: '', //业务ID
                              customerId: '', //客户ID
                              attachType: '0', //0：图片；1：视频
                              attachKind: '', //附件种类
                              type: '名片', //图片类型
                            }}
                            onImageUploaded={this.handleImageUploaded}
                          />
                        </Col>
                        <Col span={4}>
                          <ImageUploader
                            fieldName="银行卡"
                            label="银行卡"
                            maxCount={1}
                            size="large"
                            showRemoveIconType={true}
                            onRemoveImage={this.handleRemoveImage}
                            fileList={this.state.fileList.bankCardImg}
                            attachmentData={{
                              projectId: '', //业务ID
                              customerId: '', //客户ID
                              attachType: '0', //0：图片；1：视频
                              attachKind: '', //附件种类
                              type: '银行卡', //图片类型
                            }}
                            onImageUploaded={this.handleImageUploaded}
                          />
                        </Col>
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={12}>
                      <FormItem label="合作协议" {...formItemLayout}>
                        <Upload {...agreementFileUploadProps}>
                          <Button icon="upload">上传文件</Button>
                          <div style={{ lineHeight: '40px', color: '#999999' }}>
                            支持扩展名 .zip .doc .docx .pdf .jpg .png
                          </div>
                        </Upload>
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={12}>
                      <FormItem label="其他附件" {...formItemLayout}>
                        <Upload {...otherFileUploadProps}>
                          <Button icon="upload">上传文件</Button>
                          <div style={{ lineHeight: '40px', color: '#999999' }}>
                            支持扩展名 .zip .doc .docx .pdf .jpg .png
                          </div>
                        </Upload>
                      </FormItem>
                    </Col>
                  </Row>
                </div>
              )}
            </Form>
          </Row>
        </Card>
        {channelDetails && (
          <Card title="代理权限信息修改">
            <ChannelProductEditor
              channelDetailsState={4}
              channelDetailsProductList={channelDetails.productList}
              // wrappedComponentRef={this.saveFormRef}
            />
          </Card>
        )}

        <Modal
          title="等级说明"
          visible={this.state.dealerLevel}
          footer={null}
          keyboard={true}
          onCancel={this.handleCancelDealerLevel}
        >
          <Description />
        </Modal>
        <FooterToolbar style={{ width: this.state.width }}>
          <Button onClick={this.handleCallback}>返回</Button>
          <Button
            type="primary"
            onClick={this.handleSubmitStep}
            loading={channelLoading}
            style={{ marginLeft: '10px' }}
          >
            提交
          </Button>
        </FooterToolbar>
      </PageHeaderLayout>
    );
  }
}
